package top.superflow.flow.runtime.flow

import top.superflow.exception.Exceptable
import top.superflow.flow.runtime.inf.defaults.DefaultGeneralRequest
import top.superflow.flow.runtime.inf.{GeneralRequest, GeneralResponse, Session}
import top.superflow.lang.{CollectionUtils, StringUtils}

import scala.beans.BeanProperty
import scala.collection.mutable

class FlowRequest extends DefaultGeneralRequest with Exceptable{

  @BeanProperty
  var session : Session = _



  val allRequests : mutable.LinkedHashMap[String, GeneralRequest] = mutable.LinkedHashMap[String, GeneralRequest]()

  def getLastRequest : GeneralRequest = {
    if(CollectionUtils.isEmpty(allRequests)){
      return null
    }

    allRequests.last._2
  }

  def getRoutePath : Iterable[String] = allRequests.keys

  def getAllReports : Map[String, GeneralRequest] = allRequests.toMap

  def getFirstRequest : GeneralRequest = {
    if(CollectionUtils.isEmpty(allRequests)){
      return null
    }

    val firstRoute = allRequests.keysIterator.next()
    allRequests.get(firstRoute).get
  }

  def addRequest(routeKey : String, generalRequest : GeneralRequest): Unit ={
    if(StringUtils.isBlank(routeKey)){
      throwRequestUnsupportedException("The route should not be blank!")
    }

    if(allRequests.contains(routeKey)){
      throwRequestUnsupportedException("The is already a request for the route key {}, please rename the route in the route configuration", routeKey)
    }

    allRequests += (routeKey -> generalRequest)
  }


  private def addRequests(requests : Map[String, GeneralRequest]) :Unit = {
    if(CollectionUtils.isEmpty(requests)){
      return
    }
    this.allRequests ++= requests
  }

  def getRouteRequest(routeName : String) : Option[GeneralRequest] = {
    allRequests.get(routeName)
  }

  override def clone(): FlowRequest = {
    val flowRequest = new FlowRequest

    flowRequest.addRequests(this.allRequests.toMap)

    flowRequest
  }

}
